<template>
	<view>

		<view>
			<view class="main_body">
				<view>
					<!-- 左侧列表内容部分 -->
					<scroll-view enable-back-to-top :scroll-into-view="toView" scroll-y="true" scroll-with-animation="true">
						<view style="height:700px;overflow: auto;">
							<view class="contain">
								<view class="otherItem" @tap="add_new">
									<image src="/static/images/invite_theme@2x.png" data-username="name"></image>
									<text>添加好友</text>
								</view>
								<view class="otherItem" @tap="into_groups">
									<image src="/static/images/group@2x.png"></image>
									<text>群组</text>
								</view>
								<view class="otherItem" @tap="into_friendNot">
									<image src="/static/images/notification.png"></image>
									<text>加好友申请</text>
									<text v-if="messageNum > 0" class="notification_dot">{{ messageNum }}</text>
								</view>
								<view class="otherItem" @tap="into_groupNot">
									<image src="/static/images/groupTheme.png"></image>
									<text>加群组申请</text>
									<text v-if="groupInviteNum > 0" class="notification_dot">{{ groupInviteNum }}</text>
								</view>
							</view>
							<view style="margin-bottom: 15px;">
								<view v-for="(group, id) in listMain" :key="id" :id="'inToView'+group.id" :data-id="group.id">
									<view class="address_top">{{group.region}}</view>
									<view v-for="(item, brandId) in group.brands" :key="brandId">
										<!-- <swipe-delete> -->
										<view class="tap_mask" @tap.stop="into_room" :data-nickname="item.nickname" :data-username="item.name">
											<view class="otherItem">
												<image :src="item.imgurl" style="border-radius: 17%;"></image>
												<text>{{item.nickname}}</text>
											</view>
										</view>
										<!-- </swipe-delete> -->
									</view>
								</view>
								<view style="height: 200px;width: 100%;"></view>
							</view>

						</view>
						
					</scroll-view>
					<!-- 右侧字母导航 -->
					<view class="orientation_region">
						<!--  <view class="orientation">#</view> -->
						<block v-for="(item, id) in listMain" :key="id">
							<view :class="'orientation_city ' + (isActive==item.id ? 'active':'' )" @tap="scrollToViewFn" :data-id="item.id">{{item.region}}</view>
						</block>
					</view>
				</view>
			</view>
		</view>

		<!-- <view class="mask" bindtap="close_mask" wx:if="{{show_mask}}"></view> -->

		<view :class="isIPX?'chatRoom_tab_X':'chatRoom_tab'">
			<view class="tableBar" @tap="tab_chat">
				<view v-if="unReadSpotNum > 0 || unReadSpotNum == '99+'" :class="'em-unread-spot ' + (unReadSpotNum == '99+'?'em-unread-spot-litleFont':'')">{{ unReadSpotNum }}</view>
				<image :class="unReadSpotNum > 0 || unReadSpotNum == '99+'? 'haveSpot': ''" src="/static/bottom/xiaoxi.png"></image>
				<text style="font-size: 13px;">聊天</text>
			</view>

			<view class="tableBar">
				<view v-if="unReadTotalNotNum > 0" class="em-unread-spot">{{ unReadTotalNotNum }}</view>
				<image :class="unReadTotalNotNum > 0 ? 'haveSpot': ''" src="/static/bottom/tongxunlured.png"></image>
				<text style="font-size: 13px;">通讯录</text>
			</view>

			<!-- <view class="tableBar" @tap="tab_notification">
				<view></view>
				<image :class="unReadTotalNotNum > 0 ? 'haveSpot': ''" src="/static/bottom/faxian.png"></image>
				<text style="font-size: 13px;">发现</text>
			</view> -->

			<view class="tableBar" @tap="tab_setting">
				<image src="/static/bottom/my.png"></image>
				<text style="font-size: 13px;">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
	var timer = null //时间定时器
	let WebIM = require("../../utils/WebIM")["default"];
	let disp = require("../../utils/broadcast");
	let systemReady = false;
	let canPullDownreffesh = false;
	let oHeight = [];
	import swipeDelete from "../../comps/swipedelete/swipedelete";

	export default {
		data() {
			return {
				search_btn: true,
				search_friend: false,
				show_mask: false,
				myName: "",
				member: [],
				messageNum: "",
				//加好友申请数
				unReadSpotNum: 0,
				groupInviteNum: '',
				//未读消息数
				unReadNoticeNum: 0,
				//加群通知数
				unReadTotalNotNum: 0,
				//总通知数：加好友申请数 + 加群通知数
				isActive: null,
				listMain: [],
				listTitles: [],
				toView: 'inToView0',
				oHeight: [],
				scroolHeight: 0,
				show_clear: false,
				isHideLoadMore: true,
				isIPX: false,
				gotop: false,
				input_code: "",
				showFixedTitile: false,
				nowname: '',
				nowpsw: '',
				grant_type: "password",
				clickshow : true,
			};
		},

		components: {
			swipeDelete
		},
		props: {},

		onLoad(option) {
			const me = this;
			const app = getApp().globalData;
			//监听加好友申请
			console.log(me.messageNum, getApp().globalData.saveFriendList.length)
			disp.on("em.subscribe", function() {
				me.setData({
					messageNum: getApp().globalData.saveFriendList.length,
					unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length,

				});
				console.log(me.messageNum)
				me.messageNum = me.messageNum
			});

			disp.on("em.contacts.remove", function(message) {
				var pageStack = getCurrentPages();

				if (pageStack[pageStack.length - 1].route === me.__route__) {
					me.getRoster();
				}
			}); //监听未读“聊天”

			disp.on("em.unreadspot", function() {
				me.setData({
					unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum
				});
			}); //监听未读加群“通知”数

			disp.on("em.invite.joingroup", function() {
				me.setData({
					unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
					unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
				});
			});
			disp.on("em.subscribed", function() {
				var pageStack = getCurrentPages();
				if (pageStack[pageStack.length - 1].route === me.__route__) {
					me.getRoster();
				}
			});
			// 监听被解除好友
			disp.on("em.unsubscribed", function() {
				var pageStack = getCurrentPages();
				if (pageStack[pageStack.length - 1].route === me.__route__) {
					me.getRoster();
				}
			});
			this.setData({
				myName: option.myName
			});
			this.myName = uni.getStorageSync('name')
		},
		onUnload() {
			clearTimeout(timer)
		},
		onHide() {
			clearTimeout(timer)
		},
		onShow() {

			this.nowname = uni.getStorageSync('name')
			this.nowpsw = uni.getStorageSync('psw')
			getApp().globalData.conn.open({
				apiUrl: WebIM.config.apiURL,
				user: this.nowname.toLowerCase(),
				pwd: this.nowpsw,
				grant_type: this.grant_type,
				appKey: WebIM.config.appkey
			});
			console.log(this.nowname, this.nowpsw)
			this.myName = uni.getStorageSync('name')
			console.log(this.myName)

			let token = uni.getStorageSync('token')
			let name = uni.getStorageSync('myUsername')
			let options = {
				userName: this.myName
			}
			console.log(options)
			WebIM.conn.getGroup(options).then((res) => {
				console.log(res)
			})
			uni.request({
				url: this.G_base + '/api/lz/qzmsg',
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded',
					'Authori-zation': 'Bearer ' + token
				},
				data: {
					account: name
				},
				success: res => {
					this.groupInviteNum = res.data.data.length
				}
			})
			this.unReadTotalNotNum = getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
			this.setData({
				messageNum: getApp().globalData.saveFriendList.length,
				unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
				unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
				unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
			});

			if (getApp().globalData.isIPX) {
				this.setData({
					isIPX: true
				});
			}

			this.getRoster();
		},

		methods: {
			//
			into_groupNot() {
				uni.navigateTo({
					url: "/pages/notification_groupDetail/groups?myName=" + this.myName
				});
			},
			getRoster() {
				let me = this;
				let rosters = {
					success(roster) {
						var member = [];

						for (let i = 0; i < roster.length; i++) {
							if (roster[i].subscription == "both") {
								member.push(roster[i]);
							}
						}

						uni.setStorage({
							key: "member",
							data: member
						});
						me.setData({
							member: member
						});

						if (!systemReady) {
							disp.fire("em.main.ready");
							systemReady = true;
						}

						me.getBrands(member);
					},

					error(err) {
						console.log("[main:getRoster]", err);
					}

				}; // WebIM.conn.setPresence()

				WebIM.conn.getRoster(rosters);
			},

			moveFriend: function(message) {
				let me = this;
				let rosters = {
					success: function(roster) {
						var member = [];

						for (let i = 0; i < roster.length; i++) {
							if (roster[i].subscription == "both") {
								member.push(roster[i]);
							}
						}

						me.setData({
							member: member
						});
					}
				};

				if (message.type == "unsubscribe" || message.type == "unsubscribed") {
					WebIM.conn.removeRoster({
						to: message.from,
						success: function() {
							WebIM.conn.unsubscribed({
								to: message.from
							});
							WebIM.conn.getRoster(rosters);
						}
					});
				}
			},
			handleFriendMsg: function(message) {
				uni.showModal({
					title: "添加好友请求",
					content: message.from + "请求加为好友",
					success: function(res) {
						if (res.confirm == true) {
							WebIM.conn.subscribed({
								to: message.from,
								message: "[resp:true]"
							});
							WebIM.conn.subscribe({
								to: message.from,
								message: "[resp:true]"
							});
						} else {
							WebIM.conn.unsubscribed({
								to: message.from,
								message: "rejectAddFriend"
							});
						}
					},
					fail: function(err) {}
				});
			},
			delete_friend: function(event) {
				const me = this;
				var delName = event.currentTarget.dataset.username;
				var myName = uni.getStorageSync("myUsername"); // 获取当前用户名

				uni.showModal({
					title: "确认删除好友" + delName,
					cancelText: "取消",
					confirmText: "删除",

					success(res) {
						if (res.confirm == true) {
							WebIM.conn.removeRoster({
								to: delName,
							});
							uni.showToast({
								title: "删除成功",
							});
							// 删除好友后 同时清空会话
							uni.setStorageSync(delName + myName, "");
							uni.setStorageSync("rendered_" + delName + myName, "");
							me.getRoster();
							disp.fire('em.main.deleteFriend')
						}
					}

				});
			},
			into_friendNot: function() {
				uni.navigateTo({
					url: "../notification_friendDetail/friendDetail?myName=" + uni.getStorageSync("myUsername")
				});
			},
			openSearch: function() {
				this.setData({
					search_btn: false,
					search_friend: true,
					show_mask: true,
					gotop: true
				});
			},
			clearInput: function() {
				this.setData({
					input_code: '',
					show_clear: false
				});
			},
			onInput: function(e) {
				let inputValue = e.detail.value;

				if (inputValue) {
					this.setData({
						show_clear: true
					});
				} else {
					this.setData({
						show_clear: false
					});
				}
			},
			cancel: function() {
				this.setData({
					search_btn: true,
					search_friend: false,
					gotop: false //show_mask: false

				});
				this.getBrands(this.member);
			},
			onSearch: function(val) {
				let searchValue = val.detail.value;
				let member = this.member;
				let serchList = [];
				member.forEach((item, index) => {
					if (String(item.name).indexOf(searchValue) != -1) {
						serchList.push(item);
					}
				});
				this.getBrands(serchList);
			},
			add_new: function() {
				uni.navigateTo({
					url: "../add_new/add_new"
				});
			},
			tab_chat: function() {
				let that=this;
				if(that.clickshow) {
					that.clickshow = false;
					uni.redirectTo({
						url: "../chat/chat"
					});
					setTimeout(function () {
						that.clickshow = true;
					}, 1500)
				} else {
					//如果一直走else分支可能是你没有在页面的data下面挂载clickshow:true,不然一直都会走else
					uni.showToast({
						title:'请勿频繁点击',
						icon:'none'
					})
				}
			},
			close_mask: function() {
				this.setData({
					search_btn: true,
					search_friend: false //show_mask: false

				});
			},
			tab_setting: function() {
				let that=this;
				if(that.clickshow) {
					that.clickshow = false;
					uni.redirectTo({
						url: "../setting/setting"
					});
					setTimeout(function () {
						that.clickshow = true;
					}, 1500)
				} else {
					//如果一直走else分支可能是你没有在页面的data下面挂载clickshow:true,不然一直都会走else
					uni.showToast({
						title:'请勿频繁点击',
						icon:'none'
					})
				}
			},
			tab_notification: function() {
				uni.redirectTo({
					url: "../faxian/newfaxian"
				});
			},
			into_inform: function() {
				uni.navigateTo({
					url: "../inform/inform?myName=" + this.myName //uni.getStorageSync("myUsername")

				});
			},
			into_groups: function() {
				uni.navigateTo({
					url: "../groups/groups?myName=" + this.myName
				});
			},
			into_room: function(event) {
				uni.setStorageSync('danren', '1')
				var nameList = {
					myName: this.myName,
					your: event.currentTarget.dataset.username
				};
				// console.log(nameList)
				uni.navigateTo({
					url: "../chatroom/chatroom?username=" + JSON.stringify(nameList)+"&nickname="+event.currentTarget.dataset.nickname
				});
			},
			into_info: function(event) {
				uni.navigateTo({
					url: "../friend_info/friend_info?yourname=" + event.target.dataset.username
				});
			},
			//点击右侧字母导航定位触发
			scrollToViewFn: function(e) {
				let that = this;
				let _id = e.target.dataset.id;

				for (let i = 0; i < that.listMain.length; ++i) {
					if (that.listMain[i].id === _id) {
						that.setData({
							isActive: _id,
							toView: 'inToView' + _id
						});
						break;
					}
				}
			},

			// 处理数据格式，及获取分组高度
		 async getBrands(member) {
				for (let i = 0; i < member.length; i++) {
					let token = uni.getStorageSync('token')
					uni.request({
						url: this.G_base + '/api/lz/ltzh',
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authori-zation': 'Bearer ' + token
						},
						data: {
							list: member[i].name,
							status: 1
						},
						processData: true,
						success: res => {
							member[i].imgurl = res.data.data.useravatar
							member[i].nickname = res.data.data.nickname
						}
					})
				}
				timer = setTimeout(() => {
					const that = this;
					const reg = /[a-z]/i; // member = [
					// 	{
					// 		groups: [],
					// 		jid: "easemob-demo#chatdemoui_zdtest2@easemob.com",
					// 		name: "adtest2",
					// 		subscription:"both"
					// 	}
					// ]

					member.forEach(item => {
						if (reg.test(item.name.substring(0, 1))) {
							item.initial = item.name.substring(0, 1).toUpperCase();
						} else {
							item.initial = '#';
						}
					});
					member.sort((a, b) => a.initial.charCodeAt(0) - b.initial.charCodeAt(0));
					var someTtitle = null;
					var someArr = [];

					for (var i = 0; i < member.length; i++) {
						var newBrands = {
							brandId: member[i].jid,
							name: member[i].name,
							imgurl: member[i].imgurl,
							nickname: member[i].nickname,
						};
						if (member[i].initial == '#') {
							if (!lastObj) {
								var lastObj = {
									id: i,
									region: '#',
									brands: [],
								};
							}

							lastObj.brands.push(newBrands);
						} else {
							if (member[i].initial != someTtitle) {
								someTtitle = member[i].initial;
								var newObj = {
									id: i,
									region: someTtitle,
									brands: [],
								};
								someArr.push(newObj);
							}

							newObj.brands.push(newBrands);
						}
					}

					;
					someArr.sort((a, b) => a.region.charCodeAt(0) - b.region.charCodeAt(0));

					if (lastObj) {
						someArr.push(lastObj);
					} //  someArr = [
					// 	{
					//         id: "1", region: "A",
					//         brands: [
					//           	{ brandId: "..", name: "阿明" },
					//           	{ brandId: "..", name: "奥特曼" },
					//           	{ brandId: "..", name: "安庆" },
					//           	{ brandId: "..", name: "阿曼" }
					//         ]
					//     },
					// ]
					//赋值给列表值

					this.listMain = someArr
					that.setData({
						listMain: someArr
					}); //赋值给当前高亮的isActive
					that.setData({
						isActive: someArr.length > 0 ? someArr[0].id : '',
					}); //计算分组高度,uni.createSelectotQuery()获取节点信息

					let number = 0;

				 for (let j = 0; j < someArr.length; ++j) {
						const query = uni.createSelectorQuery().in(this)
						query.select(`#inToView${someArr[j].id}`).boundingClientRect(rect => {
							if (rect) {
								number = rect.height + number;
								var newArry = [{
									'height': number,
									'key': rect.dataset.id,
									"name": someArr[j].region
								}];
								oHeight = oHeight.concat(newArry);
							} else {
								this.$nextTick(() => {
									this.getBrands(member)
								})
							}
						}).exec();
					}

					;
				}, 1000)
			}
		}
	};
</script>
<style>
	@import "./notification.css";
	@import "./main.css";
</style>
